package com.demo.function.excel.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.demo.function.excel.easyexcel.handler.MergeCellWriteHandler;
import com.demo.function.excel.easyexcel.pojo.User;
import com.demo.function.excel.easyexcel.pojo.ValidateResult;
import com.demo.function.excel.easyexcel.utils.ExcelReadUtil;
import com.google.common.collect.ArrayListMultimap;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.LongStream;

@Slf4j
public class EasyExcelService {

    /**
     * 大数据量导出excel
     * @param max 初始化记录数
     */
    public void writeBigDataExcel(int max) {
        List<User> list = LongStream.range(1, max).mapToObj(i -> {
            User user = new User();
            user.setId(i);
            user.setUserId(i);
            user.setUserName("程某某" + i);
            user.setAddress("中国广东省广州市天河区xx街道xx路xx号" + i);
            user.setSex("男" + i);
            user.setPhone("13800138000" + "_" + i);
            user.setHeight(180);
            user.setWeight(100);
            user.setIdNo(440106999988887777L);
            return user;
        }).collect(Collectors.toList());

        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        String projectPath = System.getProperty("user.dir");
        log.info("projectPath:" + projectPath);

        long currentTimeMillis = System.currentTimeMillis();
        try (ExcelWriter writer = EasyExcel.write(projectPath + "/excel.xlsx").build()) {
            writer.write(list, writeSheet);
        }
        log.info("导出excel耗时：" +(System.currentTimeMillis() - currentTimeMillis));
    }

    /**
     * 大数据量导入
     * @param filePath  文件路径
     * @return 返回数据集合
     * @throws FileNotFoundException 找不到文件异常
     */
    public List<User> importBigDataExcel(String filePath) throws FileNotFoundException {
        ValidateResult<User> result = ExcelReadUtil.read(new FileInputStream(filePath), User.class, true, 1);
        return result.getSuccessList();
    }

    /**
     * 动态单元格合并
     */
    public void mergeCell() {
        ArrayListMultimap<Integer, User> userMap = ArrayListMultimap.create();
        for (int i = 0; i < 10; i++) {
            int mod = i % 3;
            if (mod == 0) {
                User user = new User();
                user.setUserId((long) mod);
                user.setUserName("user0");
                user.setSex("男");
                user.setAddress("地址" + i);
                userMap.put(mod, user);
            } else if (mod == 1) {
                User user = new User();
                user.setUserId((long) mod);
                user.setUserName("user1");
                user.setSex("女");
                user.setAddress("地址" + i);
                userMap.put(mod, user);
            } else {
                User user = new User();
                user.setUserId((long) mod);
                user.setUserName("user2");
                user.setSex("未知");
                user.setAddress("地址" + i);
                userMap.put(mod, user);
            }
        }


        //需要合并的列
        int[] mergeColumnIndex = {1, 3};
        //从第一行后开始合并
        int mergeRowIndex = 1;
        // 调用合并单元格
        MergeCellWriteHandler mergeCellWriteHandler = new MergeCellWriteHandler(mergeColumnIndex, mergeRowIndex);

        //内容策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 设置水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(null, contentWriteCellStyle);

        WriteSheet writeSheet = EasyExcel.writerSheet()
                .registerWriteHandler(mergeCellWriteHandler)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .build();

        String projectPath = System.getProperty("user.dir");
        log.info("projectPath:" + projectPath);
        try (ExcelWriter writer = EasyExcel.write(projectPath + "/excel.xlsx").head(User.class).build()) {
            Set<Integer> set = userMap.keySet();
            for (Integer key : set) {
                List<User> users = userMap.get(key);
                writer.write(users, writeSheet);
            }
        }
    }
}
